//
//  SelectPicScrollView.m
//  ChongDingTest
//
//  Created by luyee on 2020/9/2.
//  Copyright © 2020 luyee. All rights reserved.
//

#import "SelectPicScrollView.h"
#import <SDWebImage.h>
#import "HeapListModels.h"
#import <Masonry.h>

@interface SelectPicScrollView()<CALayerDelegate>{
    
    CGFloat                     _beginTimeStamp;
    CGPoint                     _beginPt;
    CGPoint                     _currentImgCenter;
    UIView*                     _currentView;
    BOOL                        _moveYes;
    NSMutableArray *     _dataArray;
    NSMutableArray *     _picViewArray;
    NSInteger                  _currentIndex;
    
    
}
@end

@implementation SelectPicScrollView{
    CGAffineTransform maxTrans;
}

- (void)reload:(NSMutableArray*)arr{
    [_dataArray addObjectsFromArray:arr];
}

- (void)refresh:(NSMutableArray *)arr {
    _currentIndex = 0;
    if (_dataArray && _dataArray.count) {
        [_dataArray removeAllObjects];
        [_dataArray addObjectsFromArray:arr];
        NSInteger count = _picViewArray.count < _dataArray.count ? _picViewArray.count : _dataArray.count;
        for (NSInteger i = 0; i < count; i ++) {
            UIView *view1 = _picViewArray[i];
            UIImageView *imgView1 = [view1 viewWithTag:7];
            UILabel *label1 = [view1 viewWithTag:8];
            HeapItemModel *model = _dataArray[2];
            NSString *imgUrlStr = model.thumb;
            [imgView1 sd_setImageWithURL:[NSURL URLWithString:imgUrlStr]];
            label1.text = model.title;
        }
    } else {
        _currentIndex = 0;
        _dataArray = [NSMutableArray array];
        [_dataArray addObjectsFromArray:arr];
        _picViewArray = [NSMutableArray array];
        [self createView];
    }
    
}

#pragma mark - -
-(void)createView{
    NSInteger picCount;
    if (_dataArray.count<kCurrentViewNum) {
        picCount = _dataArray.count;
    }else{
        picCount = kCurrentViewNum;
    }
   
    for (int i = 0; i<picCount; i++) {
        UIView *view = [self addViewWithdataNum:i];
//        [self insertSubview:view atIndex:0];
        [self addSubview:view];
        [self sendSubviewToBack:view];
        [_picViewArray addObject:view];
        view.tag = i;
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_centerY).mas_offset(120);
            make.left.equalTo(self.mas_left).mas_offset(20);
            make.centerX.equalTo(self.mas_centerX);
            make.height.equalTo(view.mas_width).mas_offset(60);
        }];
        if (i == 0) {
            _currentView = view;
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self->_currentImgCenter = self->_currentView.center;
                    self->maxTrans = view.transform;
                    
                });
            });
        } else {
            view.transform = CGAffineTransformScale(maxTrans, 1 - 0.05 * i, 1 - 0.05 * i);
            [view mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.mas_centerY).mas_offset(120 + 15 * i);
            }];
        }
    }
}


#pragma mark - - 创建
-(UIView *)addViewWithdataNum:(NSInteger)dataNum{

    UIView *view = [[UIImageView alloc]init];
    view.backgroundColor = [UIColor whiteColor];
    view.frame = CGRectMake(
                            kFirstViewFrameX,
                            kFirstPicFrameY,
                            kWidth-kFirstViewFrameX*2,
                            kWidth-kFirstViewFrameX*2 + 60);
    view.layer.cornerRadius =10;
    view.layer.masksToBounds = NO;
    view.layer.shadowOffset = CGSizeZero;//默认为0,-3
    view.layer.shadowColor = [UIColor grayColor].CGColor;
    view.layer.shadowOpacity = 1;//阴影透明度，默认0
   
    HeapItemModel *model = _dataArray[dataNum];
    
    UIImageView *imgview = [[UIImageView alloc] init];
    imgview.backgroundColor = [UIColor orangeColor];
    [view addSubview:imgview];
    
    NSString *imgUrlStr = model.thumb;
    [imgview sd_setImageWithURL:[NSURL URLWithString:imgUrlStr]];
    imgview.tag = 7;
    imgview.contentMode = UIViewContentModeScaleAspectFit;
    
    UILabel *label = [[UILabel alloc]init];
    label.backgroundColor = [UIColor whiteColor];
    label.text = model.title;
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.tag = 8;
    [view addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(view);
        make.left.equalTo(view).mas_offset(20);
        make.right.equalTo(view).mas_offset(-20);
        make.height.mas_equalTo(60.f);
    }];
    
    [imgview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(view);
        make.bottom.equalTo(label.mas_top);
    }];
    
    CGRect bounds = view.bounds;
    bounds.size.height -= 60;
    [self cornerRadios:imgview withBounds:bounds];
    
    maxTrans = view.transform;
    
    return view;
}

#pragma mark - - 准备互动
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    _beginTimeStamp = event.timestamp;
    _beginPt = [[touches anyObject] locationInView:self];
    
    if ([_delegate respondsToSelector:@selector(touched)]) {
        [_delegate touched];
    }
    
    //控件滑动范围
    if (kBeginPtYRange)
        _moveYes = YES;
    else
        _moveYes = NO;
}

#pragma mark - - 正在互动
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint pt = [[touches anyObject] locationInView:self];
    CGFloat x = pt.x - _beginPt.x;
    CGFloat y = pt.y - _beginPt.y;
    
    //图片范围内响应
    if (_moveYes == YES) {
        _currentView.center = CGPointMake(_currentImgCenter.x + x,_currentImgCenter.y + y);
        _currentView.transform=CGAffineTransformMakeRotation(x/1000);
    }
}

#pragma mark - - 结束互动
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGPoint pt = [[touches anyObject] locationInView:self];
    CGFloat distanceX =  pt.x -_beginPt.x;
    CGFloat timeStamp = _beginTimeStamp - event.timestamp;
    
    //快速小范围滑动/*1*/
    if (fabs(timeStamp)<0.12f&&fabs(distanceX)>25) {
        if (distanceX>0){
            [self moveViewX:kRemoveRightX Y:pt.y andRemoveView:YES];
            if ([_delegate respondsToSelector:@selector(rightMoveEndWithIndex:)]) {
                [_delegate rightMoveEndWithIndex:_currentIndex-1];
            }
            
        }else{
            [self moveViewX:kRemoveLeftX Y:pt.y andRemoveView:YES];
            if ([_delegate respondsToSelector:@selector(leftMoveEndWithIndex:)]) {
                [_delegate leftMoveEndWithIndex:_currentIndex-1];
            }
        }
    
    //慢速大范围/*1*/
    }else{
        //向右
        if (distanceX>0) {
            if (distanceX>_currentView.frame.size.width/2) {
                [self moveViewX:kRemoveRightX Y:pt.y andRemoveView:YES];
                if ([_delegate respondsToSelector:@selector(rightMoveEndWithIndex:)]) {
                    [_delegate rightMoveEndWithIndex:_currentIndex-1];
                }
        
            }else{
                [self moveViewX:_currentImgCenter.x Y:_currentImgCenter.y andRemoveView:NO];
            }
            
        //向左
        }else{
            if ( fabs(distanceX)>_currentView.frame.size.width/2) {
                [self moveViewX:kRemoveLeftX Y:pt.y andRemoveView:YES];
                if ([_delegate respondsToSelector:@selector(leftMoveEndWithIndex:)]) {
                    [_delegate leftMoveEndWithIndex:_currentIndex-1];
                }
            
            }else{
                [self moveViewX:_currentImgCenter.x Y:_currentImgCenter.y andRemoveView:NO];
            }
        }
    } /*1*/
}

- (void)cornerRadios:(UIView *)view withBounds:(CGRect)rect {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame =  rect;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

#pragma mark - -
-(void)moveViewX:(float)x Y:(float)y andRemoveView:(BOOL)isRemove{
    [UIView animateWithDuration:0.3 animations:^{
        self->_currentView.center = CGPointMake(x, y);
        self->_currentView.transform=CGAffineTransformMakeRotation(0);
 
    } completion:^(BOOL finished) {
    }];
    
    if (isRemove == YES) {
        if (_dataArray.count == 0) {
            self.userInteractionEnabled = NO;
        }else{
            self.userInteractionEnabled = YES;
            [self changeMoveView];
        }
    }
}

#pragma mark - -
-(void)changeMoveView{
    UIView *tmpView = _picViewArray[0];
    [_picViewArray removeObjectAtIndex:0];
    [_dataArray removeObjectAtIndex:0];
    _currentIndex++;
    
    NSInteger picCount;
    if (_dataArray.count < kCurrentViewNum) {
        picCount = _dataArray.count;
        [tmpView removeFromSuperview];
        
    }else{
        picCount = kCurrentViewNum;
        [_picViewArray addObject:tmpView];
    }
    
    //
    for (int i = 0; i < picCount; i++) {
        UIView *view1 = _picViewArray[i];
        CGAffineTransform transform;
        if (i == 0) {
            transform = maxTrans;
            
        } else if (i < kCurrentViewNum - 1) {
            transform = CGAffineTransformScale(self->maxTrans, 0.95, 0.95);
        } else {
            view1.alpha = 0;
            [self sendSubviewToBack:view1];
            transform = CGAffineTransformScale(maxTrans, 0.9, 0.9);
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        view1.alpha = 1;
                    });
                });
            });

            UIImageView *imgView1 = [view1 viewWithTag:7];
            UILabel *label1 = [view1 viewWithTag:8];
            HeapItemModel *model = _dataArray[2];
            NSString *imgUrlStr = model.thumb;
            [imgView1 sd_setImageWithURL:[NSURL URLWithString:imgUrlStr]];
            label1.text = model.title;
        }
        
        [UIView animateWithDuration:0.3 animations:^{
            view1.transform = transform;
            [view1 mas_updateConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.mas_centerY).mas_offset(120 + 15 * i);
            }];
        } completion:^(BOOL finished) {
            if (i == 0) {
                self->_currentView = view1;
                self->_currentImgCenter = self->_currentView.center;
                
            }
        }];
    }
}

- (void)displayLayer:(CALayer *)layer{
    
}

//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
//    if (!self.userInteractionEnabled || [self isHidden] || self.alpha <= 0.01) {
//        return nil;
//    }
//
//    //判断当前视图是否在点击范围内
//    if ([self pointInside:point withEvent:event]) {
//        //遍历当前对象的子视图(倒序)
//        __block UIView *hit = nil;
//        [self.subviews enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            //坐标转换，把当前坐标系上的点转换成子控件坐标系上的点
//            CGPoint convertPoint = [self convertPoint:point toView:obj];
//            //调用子视图的hitTest方法，判断自己的子控件是不是最适合的View
//            hit = [obj hitTest:convertPoint withEvent:event];
//            //如果找到了就停止遍历
//            if (hit) *stop = YES;
//        }];
//
//        //返回当前的视图对象
//        return hit?hit:self;
//    }else {
//        return nil;
//    }
//}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGFloat x1 = point.x;
    CGFloat y1 = point.y;
    if (x1 > _currentView.frame.origin.x && y1 > _currentView.frame.origin.y && x1 < _currentView.frame.origin.x + _currentView.frame.size.width && y1 < _currentView.frame.origin.y + _currentView.frame.size.height) {
        return YES;
    }
    else{
        return NO;
    }
}

@end
